package com.duoec.dw.lineage.service.analyser.from;

import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSubqueryTableSource;
import com.alibaba.druid.sql.ast.statement.SQLWithSubqueryClause;
import com.duoec.dw.lineage.dto.MultiTableLineageDto;
import com.duoec.dw.lineage.dto.TableLineageDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author xuwenzhen
 */
@Service
public class SubqueryTableSourceAnalyser extends BaseTableSourceAnalyser<SQLSubqueryTableSource> {
    private static final Logger logger = LoggerFactory.getLogger(SubqueryTableSourceAnalyser.class);

    /**
     * 获取当前类处理的类型
     *
     * @return SQLTableSource子类类型
     */
    @Override
    public Class<SQLSubqueryTableSource> getTableSourceType() {
        return SQLSubqueryTableSource.class;
    }

    /**
     * 解析 from
     *
     * @param tableSource 需要解析的from
     * @return 当前select脚本的血缘关系
     */
    @Override
    public MultiTableLineageDto analyse(SQLSubqueryTableSource tableSource, MultiTableLineageDto withAsTableLineages) {
        SQLSelect select = tableSource.getSelect();
        MultiTableLineageDto dto = new MultiTableLineageDto();

        TableLineageDto lineageDto = hiveAnalyser.analyseQuery(select.getQuery(), withAsTableLineages);
        if (lineageDto == null) {
            return dto;
        }
        String alias = tableSource.getAlias();
        if (!StringUtils.isEmpty(alias)) {
            lineageDto.setAlias(alias);
        } else {
            logger.warn("子查询没有设置别名：{}", tableSource.toString());
        }

        dto.add(lineageDto);
        return dto;
    }


}
